<?php

require_once '../config/siteConf.php';
require_once 'adminClass.php';
define ( 'SITEKEY', 'ASiteSpecificArbitraryLengthStringThatIsUsedToSeedTheHashingAlgorithm!' ); // NEVER CHANGE!

/**
 * 
 * @author Eivind Parken
 * 
 */

class user {
	private $username = '';
	private $userID = - 1;
	private $name = '';
	private $email = '';
	private $role = 'public';
	private $companyID = -1;
	// private $avatar;
	public $error ='';
	public $db;
	public $isAdmin = false;
	public $isActive = false;
	
	/**
	 * Generate a encryption
	 * @param string $string
	 */
	private function session_encrypt($string) {
		$salt = 'studrabbat';
		$string = md5($salt . $string);
		return $string;
	}
	/**
	 * Generates a random string
	 * @param number $length
	 * @return string
	 */
	private function generateRandomString($length = 10) {
		$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$randomString = '';
		for ($i = 0; $i < $length; $i++) {
			$randomString .= $characters[rand(0, strlen($characters) - 1)];
		}
		return $randomString;
	}
	/**
	 * Constructor 
	 * @param pdoObject $db
	 */
	function __construct($db, $username = NULL, $pwd = NULL) {
		global $_POST, $_SESSION;
		$this->db = $db;
		if(isset($_POST['username']) || isset($username)){
		
			if(isset($_POST['username'])){
				$this -> username = $_POST['username'];
			}else{
				$this -> username = $username;
			}
			$select = $db -> prepare("SELECT *, count(*) as result FROM user WHERE userName=:username AND userActivated=1");
			$select -> bindParam(':username', $this -> username);
			$select -> execute();
			$user = $select -> fetch();
			if($user){
				$uID = $user['userID'];
				$salt = $user['salt'];
				/*
				$select -> closeCursor();
				$salt = $this -> db -> prepare("SELECT salt FROM user WHERE userID=:uID");
				$salt -> bindParam(':uID', $uID);
				$salt -> execute();
				$salt = $salt -> fetch();
				if($salt){
				*/
					$query = "SELECT * FROM user WHERE userID=:uID and password=:pwd";
					$select -> prepare($query);
					$select -> bindParam(':uID', $uID);
					if(isset($pwd)){
						$password = $uID . $pwd . $salt;
					}else{
						$password = $uID . $_POST ['password'] . $salt;
					}
					$select -> bindParam ( ':pwd', hash_hmac('sha512', $password, SITEKEY ));
					$select -> execute();
					$user = $select -> fetch();
					if($user){
						if(isset($_POST['rememberme'])){
							// Generate new auth key for each log in (so old auth key can not be used multiple times in case
							// of cookie hijacking)
							$cookie_auth= $this -> generateRandomString(10) . $user['userName'];
							$auth_key = $this -> session_encrypt($cookie_auth);
							$select -> closeCursor();
							try{
								$this -> db -> beginTransaction();
								$this -> db -> query('LOCK TABLES user WRITE');
								$select -> prepare("UPDATE user SET auth_key=:authKey WHERE userName=:username");
								$select -> bindParam(':authKey', $auth_key);
								$select -> bindParam(':username', $user['userName']);
								$select -> execute();
								if($select -> rowCount() == 0){
									$this -> db -> rollback();
									$this -> query('UNLOCK TABLES');
									throw new Exception('Error while updateing AutKey');
								}else{
									setcookie("authKey", $auth_key, time() + 60 * 60 * 24 * 7, $serverPath, $serverDomain, false, true);
								}	
							} catch(Exception $e){
								echo "Error while updating AutKey".$e->getMessage();
							}
						}
						$this -> username = $user['userName'];
						$this -> userID = $user['userID'];
						$this -> name = $user['name'];						
						$this -> email = $user['userEmail'];
						$this -> role = $user['role'];
						$this -> companyID = $user['companyID'];
						session_regenerate_id(true);
						$_SESSION['userID'] = $user['userID'];
						$_SESSION['userName'] = $user['userName'];
						$_SESSION['userRole'] = $user['role'];
						$_SESSION['userLastactive'] = time();
						
						return true;						
					}
					/*
				}else{
					$this -> error = "Uknown password, is the username correct?";
				}
				*/
			}else{
				$this -> error = "Unknown username or password";
			}			
		}else if(isset($_POST['logout'])){
			unset($_SESSION['userID']);
		}else if(isset($_SESSION['userID'])){
			$this -> userID = $_SESSION['userID'];
			$select = $this -> db -> prepare("SELECT * FROM user WHERE userID=:uID");
			$select -> bindParam(':uID', $uID);
			$select -> execute();
			$user = $select -> fetch();
			if($user){
				$this -> username = $user['userName'];
				$this -> name = $user['name'];
				$this -> email = $user['userEmail'];
				$this -> role = $user['role'];
				$this -> companyID = $user['companyID'];
			}
		}
	}
	
	/**
	 * Add a new user
	 * @param array $userData
	 * @throws Exception 
	 */
	public function userRegistration($userData) {
		try {
			$this->db->beginTransaction ();
			$this->db->query ( 'LOCK TABLES user WRITE' );
			$query = "INSERT INTO user (companyID, name, userName, userEmail, role, userActivated)
	 				VALUES (:cID, :name, :userName, :userEmail, :role, 0)";
			$insert = $this->db->prepare ( $query );
			$insert->bindParam ( ':cID', $userData ['cID'] );
			$insert->bindParam ( ':name', $userData ['name'] );
			$insert->bindParam ( ':userName', $userData ['userName'] );
			$insert->bindParam ( 'userEmail', $userData ['userEmail'] );
			$insert->bindParam ( ':role', $userData ['role'] );
			$insert->execute ();
			if ($insert->rowCount () == 0) {
				$this->db->rollback ();
				$this->db->query ( 'UNLOCK TABLES' );
				throw new Exception ( 'Username or email already exists!' );
			}
			$insert->closeCursor ();
			$insert = $this->db->prepare ( 'SELECT LAST_INSERT_ID() AS userID' );
			$insert->execute ();
			$user = $insert->fetch ();
			if ($user) {
				$uID = $user ['userID'];
			} else {
				$this->db->rollback ();
				$this->db->query ( 'UNLOCK TABLES' );
				throw new Exception ( 'Error while getting new user id!' );
			}
			$insert->closeCursor ();
			$insert->prepare ( 'UPDATE user SET passWord=:password, salt=:salt, activationKey=:activationKey' );
			$salt = dechex ( mt_rand ( 0, 2147483647 ) ) . dechex ( mt_rand ( 0, 2147483647 ) );
			$password = $uID . $userData ['password'] . $salt;
			$insert->bindParam ( ':password', hash_hmac('sha512', $password, SITEKEY ));
			$insert->bindParam ( ':salt', $salt );
			$activationKey = md5 ( $userData ['userEmail'] . time () );
			$insert->bindParam ( ':activationKey', $activationKey );
			$insert->execute ();
			if ($insert->rowCount () == 0) {
				$this->db->rollback ();
				$this->db->query ( 'UNLOCK TABLES' );
				throw new Exception ( 'Unable to set password!' );
			}
			$completed = $this->db->commit ();
			if ($completed) {
				include_once '../functions/mail.php';
				$to = $userData ['userEmail'];
				$subject = "StudentRabbat: Epost bekreftelse";
				$body = "Hei {$userData['name']}, <br /><br />
	 			Vi trenger å få vertifisert at din epost adresse er ekte før du kan
	 			starte å bruke våre sider, vennligst klikk deg inn på linken neden for å
	 			bekrefte din epost adresse:<br />
	 			<a href='{$base_url}activate/{$activationKey}'>{$base_url}activate/{$activationKey}</a>
	 			<br /><br />
	 			Hvis du ikke har registrert deg på på studenrabatt, vennligst se bort i fra denne mailen.";
				sendActivation ( $to, $subject, $body );
			} else {
				throw new Exception ( 'Unable to commitdata to DB!' );
			}
		} catch ( Exception $e ) {
			echo "A problem have occourd please contact Admin" . $e->getMessage ();
		}
	}
	
	public function actvateUser($vertificationKey){
		$query = "SELECT count(userID) as result, userID FROM user WHERE activationKey =:key";
		$sth = $this -> db -> prepare($query);
		$sth -> bindParam(':key', $vertificationKey);
		$sth -> execute();
		$sth = $sth -> fetch();
		if($sth['result'] > 0){
			$sth = NULL;
			$query = "SELECT count(userID) as result, userID FROM user WHERE activationKey =:key AND userActivated=0";
			$sth = $this -> db -> prepare($query);
			$sth -> bindParam(':key', $vertificationKey);
			$sth -> execute();
			$sth = $sth -> fetch();
			if($sth['count'] == 1){
				$sth = NULL;
				$this->db->beginTransaction ();
				$this->db->query ( 'LOCK TABLES user WRITE' );
				$query = "UPDATE user SET userActivated=1 WHERE activationKey:Key";
				$sth -> bindParam(':key', $vertificationKey);
				$sth -> execute();
				if($sth -> rowCount() == 0){
					$this -> db -> rollback();
					$this -> db -> query('UNLOCK TABLES');
					throw new Exception('Error while updateing user!');
				}
				$this-> db -> commit();
				return 1;
			}else{
				return 2;
			}
		}else{
			return 3;
		}		
	}
	
}

?>